import axios from 'axios';
import Qs from 'qs';
import request from './request';
import loginStore from '../store/login.js';
import {Toast} from 'vant';
import router from '../router/router';
import store from '../store/store';
import {baseUrl} from "../config";

axios.defaults.withCredentials = true;
export default class Net {
    static get(url, params) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'get',
                url,
                params,
                headers: {Authorization: loginStore.state.token}
                // headers: {Authorization: ''}
            })
                .then((res) => {
                    this.successTodo(resolve, reject, res);
                })
                .catch((error) => {
                    this.errTodo(error, url);
                });
        });
    }

    // loginStore.state.token
    static post(url, params) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'post',
                url,
                data: Qs.stringify(params),
                // data: params,
                headers: {Authorization: loginStore.state.token}
                // headers: {Authorization: ''}
            })
                .then((res) => {
                    this.successTodo(resolve, reject, res);
                })
                .catch((error) => {
                    this.errTodo(error, url);
                });
        });
    }

    static upPic(url, params) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'post',
                url,
                data: Qs.stringify(params),
                // data: params,
                headers: {Authorization: loginStore.state.token}
                // headers: { Authorization: '' }
            })
                .then((res) => {
                    let retcode = parseInt(res.data.retcode);
                    if (retcode === 2000000) {
                        let data = res.data.result;
                        let param = new FormData(); //创建form对象
                        param.append('key', data.dir); //通过append向form对象添加数据
                        param.append('OSSAccessKeyId', data.accessid);
                        param.append('policy', data.policy);
                        param.append('signature', data.signature);
                        param.append('expire', data.expire);
                        param.append('callback', data.callback);
                        param.append('dir', 'admin/');
                        param.append('file', params.file);
                        // console.log(param.get('file')); //FormData私有类对象，访问不到，可以通过get判断值是否传进去
                        let config = {
                            headers: {'Content-Type': 'multipart/form-data'}
                        }; //添加请求头
                        axios
                            .post(data.host, param, config)
                            .then((res) => {
                                console.log(data.host, 11111);
                                resolve(data.host + '/' + res.data.url);
                            })
                            .catch(function (e) {
                                console.log(e);
                            });
                    } else if (retcode === 5001001) {
                        // loginStore.mutations.loginShow(loginStore.state, true);
                        reject(res.data.msg);
                    } else if (retcode === 5001002) {
                        // loginStore.mutations.reLoginShow(loginStore.state, true);
                        reject(res.data.msg);
                    } else {
                        reject(alert(res.data.msg));
                    }
                })
                .catch((error) => {
                    // this.errTodo(error, url);
                });
        });
    }

    // 处理成功方法
    static successTodo(resolve, reject, val) {
        let retcode = parseInt(val.data.retcode);
        if (retcode === 2000000) {
            resolve(val.data.result);
        } else if (retcode === 5001001) {
            if (loginStore.state.system == 9999) {
                //聚合系统
                router.push({name: 'poly-login'});
            } else {
                //普通系统
                router.push('login');
            }

            Toast(val.data.msg);
            reject(val.data.msg);
        } else if (retcode == 5001002 || retcode == 5001004) {
            // // token失效，把本地tokenarray中的对应系统删掉
            // let tokenArray = JSON.parse(localStorage.getItem('tokenArray'));
            // let system = loginStore.state.system;
            // delete tokenArray[system];
            // // 跳转welcome重新获取token
            // router.push({
            //     name: 'welcome',
            //     query: {
            //         system: system,
            //         referid: loginStore.state.refer.referid
            //     }
            // });
            //  token失效，把本地tokenarray中的对应系统删掉
            let tokenArray = JSON.parse(localStorage.getItem('tokenArray'));
            let system = loginStore.state.system;
            delete tokenArray[system];
            store.commit('setTokenArray', tokenArray);
            store.commit('setToken', '');
            store.commit('setTokenType', '');
            // window.location.href = baseUrl + '/oauth?system=' + system;
            //    非正式token
            router.push({
                name: 'welcome',
                query: {
                    system: system
                }
            });
            Toast(val.data.msg);
            reject(val.data.msg);
        } else if (retcode >= 5001003 && retcode <= 5004011) {
            Toast(val.data.msg);
            reject(val.data.msg);
        } else if (retcode >= 5004001 && retcode <= 5008001) {
            Toast(val.data.msg);
            reject(val.data.msg);
        } else if (retcode >= 3001001 && retcode <= 3001999) {
            window.location.href = '/';
            reject(val.data.msg);
        } else if (retcode >= 3002001 && retcode <= 3002999) {
            window.location.href = '/user';
            reject(val.data.msg);

        } else if (retcode == 0) {
            Toast(val.data.msg);
            reject(val.data.msg);
        } else {
            // reject(Toast(val.data.msg));
            reject(val.data.msg);
        }
    }

    // 处理异常方法
    static errTodo(error, url) {
        //非jsexception接口报错，post后端记录
        console.log(error, url);
        if (url.indexOf('jsexception') === -1) {
            request.post('/jsexception', error);
        }
        let errorCode = error.response.status;
        let errorCodeFir = (error.response.status + ``).substr(0, 1);
        let msg = '';
        // console.log(error.response.status + ``);
        if (errorCodeFir === '3') {
            msg = `${errorCode}:请刷新重试!`;
            alert(msg);
        } else if (errorCodeFir === '4') {
            msg = `${errorCode}:请刷新重试!`;
            alert(msg);
        } else if (errorCodeFir === '5') {
            msg = `${errorCode}:请刷新重试!`;
            alert(msg);
        }
    }
}
